package com.cqgcxy.auth_module.controller;

import com.cqgcxy.auth_module.dto.LoginRequest;
import com.cqgcxy.auth_module.service.AuthService;
import com.cqgcxy.common.utils.Msg;
import com.cqgcxy.auth_module.vo.UserTypeInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private final AuthService authService;

    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    @PutMapping("/login")
    public Msg login(@RequestBody @Validated LoginRequest loginRequest, HttpServletRequest request) {
        AuthService.UserData userData = authService.login(
            loginRequest.getAccount(), loginRequest.getPassword(), loginRequest.getUserType()
        );
        if (userData != null) {
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            stringRedisTemplate.opsForValue().set(token, String.valueOf(userData.getAccount()), 3600, TimeUnit.SECONDS);//将用户的ID信息存入redis缓存，并设置一小时的过期时间
            return Msg.success().add("token",token).add("info","登录成功");
        }else {
            return Msg.fail().add("info", "登录失败");
        }

//        request.getSession().setAttribute(UserSessionData.SESSION_DATA_KEY, new UserSessionData(
//            userData.getAccount(),
//            userData.getUsername(),
//            userData.getUserType()
//        ));
    }

    @PostMapping("/logout")
    public void logout(HttpSession session, SessionStatus sessionStatus) {
        session.invalidate();
        sessionStatus.setComplete();
    }

    @GetMapping("/user_type/all")
    public List<UserTypeInfo> getAllUserType() {
        return authService.getAllUserType().stream().map(userTypeData -> new UserTypeInfo(
                userTypeData.getName(), userTypeData.getFormat()
        )).collect(Collectors.toList());
    }

}
